package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import eneity.Result;
import eneity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: fxx
 * @Date: 2021/1/14 16:37
 */
@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private FriendService friendService;

    @Autowired
    private UserClient userClient;

    @PostMapping("/like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type, HttpServletRequest request){

        Claims claims= (Claims) request.getAttribute("claims_user");
        if (claims == null){
            return new Result(false, StatusCode.ERROR, "权限不足");
        }
        String userid = claims.getId();
        if (type != null){
            if (type.equals("1")){
                //添加好友
                int flag = friendService.addFriend(userid, friendid);
                if (flag == 0){
                    return new Result(false, StatusCode.ERROR, "不能重复添加好友");
                }else{
                    userClient.updatefanscountandfollowcount(userid, friendid, 1);
                    return new Result(true, StatusCode.OK, "添加成功");
                }
            }else if (type.equals("2")){
                //添加非好友
                int flag = friendService.addNoFriend(userid, friendid);
            }
            return new Result(false, StatusCode.ERROR, "参数异常");
        }else{
            return new Result(false, StatusCode.ERROR, "参数异常");
        }
    }

    @DeleteMapping("/{friendid}")
    public Result deleteFriend(@PathVariable String friendid, HttpServletRequest request){
        Claims claims= (Claims) request.getAttribute("claims_user");
        if (claims == null){
            return new Result(false, StatusCode.ERROR, "权限不足");
        }
        String userid = claims.getId();
        friendService.deleteFriend(userid, friendid);
        userClient.updatefanscountandfollowcount(userid, friendid, -1);
        return new Result(true, StatusCode.OK, "删除成功");
    }
}
